

package org.drl.tvkit.widget;

import java.util.Locale;

import org.drl.tvkit.R;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;



public class PagerTabStrip extends HorizontalScrollView implements BasePagerTabStrip {
	// @formatter:off
	private static final int[] ATTRS = new int[] {
		android.R.attr.textSize,
		android.R.attr.textColor
    };
	// @formatter:on

	private LinearLayout.LayoutParams defaultTabLayoutParams;

	private final PageListener pageListener = new PageListener();
	public OnPageChangeListener delegatePageListener;

	private LinearLayout tabsContainer;
	private VooleViewPager pager;

	private int tabCount;

	private int currentPosition = 0;
	private float currentPositionOffset = 0f;

	private Paint rectPaint;
	
	private Paint bitmapPaint;

	private int indicatorColor = 0xFF666666;
	private int underlineColor = 0x1A000000;
	private int dividerColor = 0x1A000000;

	private boolean textAllCaps = true;

	private int scrollOffset = 52;
	private int indicatorHeight = 8;
	private int underlineHeight = 2;
	private int dividerPadding = 12;

	private int tabTextSize = 30;

	private int lastScrollX = 0;

	private int tabBackgroundResId = R.drawable.background_tab;

	private Locale locale;
	
	private Bitmap UntabSelectBitmap;
	
	private Bitmap tabSelectBitmap;
	
	
	public PagerTabStrip(Context context) {
		this(context, null);
	}

	public PagerTabStrip(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public PagerTabStrip(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

		setFillViewport(true);
		setWillNotDraw(false);
		setSmoothScrollingEnabled(true);
		tabsContainer = new LinearLayout(context);
		tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
		LayoutParams _layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		tabsContainer.setLayoutParams(_layoutParams);
		tabsContainer.setGravity(Gravity.TOP);
		addView(tabsContainer);

		DisplayMetrics dm = getResources().getDisplayMetrics();

		scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
		indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm);
		underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm);
		dividerPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm);

		// get system attrs (android:textSize and android:textColor)

		TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);


		a.recycle();

		// get custom attrs

		a = context.obtainStyledAttributes(attrs, R.styleable.VooleTabStrip);

		indicatorColor = a.getColor(R.styleable.VooleTabStrip_pstsIndicatorColor, indicatorColor);
		underlineColor = a.getColor(R.styleable.VooleTabStrip_pstsUnderlineColor, underlineColor);
		dividerColor = a.getColor(R.styleable.VooleTabStrip_pstsDividerColor, dividerColor);
		indicatorHeight = a.getDimensionPixelSize(R.styleable.VooleTabStrip_pstsIndicatorHeight, indicatorHeight);
		underlineHeight = a.getDimensionPixelSize(R.styleable.VooleTabStrip_pstsUnderlineHeight, underlineHeight);
		dividerPadding = a.getDimensionPixelSize(R.styleable.VooleTabStrip_pstsDividerPadding, dividerPadding);
		scrollOffset = a.getDimensionPixelSize(R.styleable.VooleTabStrip_pstsScrollOffset, scrollOffset);
		textAllCaps = a.getBoolean(R.styleable.VooleTabStrip_pstsTextAllCaps, textAllCaps);

		a.recycle();

		rectPaint = new Paint();
		rectPaint.setAntiAlias(true);
		rectPaint.setStyle(Style.FILL);
		
		bitmapPaint = new Paint();
		bitmapPaint.setAntiAlias(true);

		tabSelectBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.widget_navigator);
		UntabSelectBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.widget_navigator_bg);

		defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
		defaultTabLayoutParams.setMargins(tabTextSize, 0, tabTextSize,15);
		defaultTabLayoutParams.gravity = Gravity.CENTER_HORIZONTAL;
		
		if (locale == null) {
			locale = getResources().getConfiguration().locale;
		}
		
		float tmpTextSize =30;
		tabTextSize = (int)tmpTextSize;
	}

	public void setViewPager(VooleViewPager pager) {
		this.pager = pager;

		if (pager.getAdapter() == null) {
			throw new IllegalStateException("ViewPager does not have adapter instance.");
		}

		pager.setOnPageChangeListener(pageListener);

		notifyDataSetChanged();
	}

	public void setOnPageChangeListener(OnPageChangeListener listener) {
		this.delegatePageListener = listener;
	}

	@SuppressLint("ResourceAsColor")
	public void notifyDataSetChanged() {
		tabsContainer.removeAllViews();
		tabCount = pager.getAdapter().getCount();
		for (int i = 0; i < tabCount; i++) {
			addTextTab(i, pager.getAdapter().getPageTitle(i).toString());
		}
		updateTabStyles();
		getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@SuppressWarnings("deprecation")
			@SuppressLint("NewApi")
			@Override
			public void onGlobalLayout() {
				if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
					getViewTreeObserver().removeGlobalOnLayoutListener(this);
				} else {
					getViewTreeObserver().removeOnGlobalLayoutListener(this);
				}
				currentPosition = pager.getCurrentItem();
				scrollToChild(currentPosition, 0);
			}
		});
		if(tabCount>0){
			for (int i = 0; i < tabCount; i++) {
				final View _view = tabsContainer.getChildAt(i);
				currentPosition = pager.getCurrentItem();
				if (_view instanceof TextView) {
					if( i==currentPosition ){
						((TextView) _view).setTextColor(Color.WHITE);
					}else{
						((TextView) _view).setTextColor(Color.argb(100, 255, 255, 255));
					}
				}
			}
		}

	}

	private void addTextTab(final int position, String title) {
		TextView tab = new TextView(getContext());
		tab.setText(title);
		tab.setGravity(Gravity.CENTER);
		tab.setSingleLine();
		tab.setTextColor(Color.WHITE);
		addTab(position, tab);
	}
	@SuppressLint("ResourceAsColor")
	private void addTab(final int position, View tab) {
		tab.setFocusable(true);
		tabsContainer.addView(tab, position, defaultTabLayoutParams);
		for (int i = 0; i < tabCount; i++) {
			View v = tabsContainer.getChildAt(i);
			if(v instanceof TextView){
				if(position == currentPosition){
					((TextView) v).setTextColor(Color.WHITE);
				}else{
					((TextView) v).setTextColor(Color.argb(100, 255, 255, 255));
				}
			}
		}
	}

	private void updateTabStyles() {

		for (int i = 0; i < tabCount; i++) {
			View v = tabsContainer.getChildAt(i);
			if (v instanceof TextView) {
				TextView tab = (TextView) v;
				tab.setTextSize(tabTextSize);
			}
		}

	}

	private void scrollToChild(int position, int offset) {
		if (tabCount == 0) {
			return;
		}
		int newScrollX = 0;
		if(tabsContainer != null && tabsContainer.getChildAt(position)!=null){
			newScrollX = tabsContainer.getChildAt(position).getLeft() + offset;
		}
		if (position > 0 || offset > 0) {
			newScrollX -= scrollOffset;
		}
		if (newScrollX != lastScrollX) {
			lastScrollX = newScrollX;
			scrollTo(newScrollX, 0);
		}
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (isInEditMode() || tabCount == 0) {
			return;
		}
		final int height = getHeight();
		rectPaint.setColor(indicatorColor);
		View currentTab = tabsContainer.getChildAt(currentPosition);
		float lineLeft = currentTab.getLeft();
		float lineRight = currentTab.getRight();
		if (currentPositionOffset > 0f && currentPosition < tabCount - 1) {
			View nextTab = tabsContainer.getChildAt(currentPosition + 1);
			final float nextTabLeft = nextTab.getLeft();
			final float nextTabRight = nextTab.getRight();
			lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
			lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);
		}
		rectPaint.setColor(underlineColor);
		for(int i=0;i<tabCount;i++){
			canvas.drawBitmap(UntabSelectBitmap,i*currentTab.getWidth()+tabTextSize+i*(tabTextSize*2), height-UntabSelectBitmap.getHeight(), null);
		}
		canvas.drawBitmap(tabSelectBitmap, lineLeft, height-tabSelectBitmap.getHeight(), null);
	}
	

	private class PageListener implements VooleViewPager.OnPageChangeListener {

		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
			currentPosition = position;
			currentPositionOffset = positionOffset;
			if(tabsContainer.getChildAt(position)!=null && tabsContainer.getChildAt(position).getWidth()!=0){
				scrollToChild(position, (int) (positionOffset * tabsContainer.getChildAt(position).getWidth()));
			}
			invalidate();
			if (delegatePageListener != null) {
				delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
			}
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			if (state == ViewPager.SCROLL_STATE_IDLE) {
				scrollToChild(pager.getCurrentItem(), 0);
			}
			if (delegatePageListener != null) {
				delegatePageListener.onPageScrollStateChanged(state);
			}
		}

		@SuppressLint("ResourceAsColor")
		@Override
		public void onPageSelected(int position) {
			for (int i = 0; i < tabCount; i++) {
				final View _view = tabsContainer.getChildAt(i);
				if(i == position){
					if (_view instanceof TextView) {
						((TextView) _view).setTextColor(Color.WHITE);
					}
				}else{
					if (_view instanceof TextView) {
						((TextView) _view).setTextColor(Color.argb(100, 255, 255, 255));
					}
				}
			}
			
			if (delegatePageListener != null) {
				delegatePageListener.onPageSelected(position);
			}
		}

	}

	public void setIndicatorColor(int indicatorColor) {
		this.indicatorColor = indicatorColor;
		invalidate();
	}

	public void setIndicatorColorResource(int resId) {
		this.indicatorColor = getResources().getColor(resId);
		invalidate();
	}

	public int getIndicatorColor() {
		return this.indicatorColor;
	}

	public void setIndicatorHeight(int indicatorLineHeightPx) {
		this.indicatorHeight = indicatorLineHeightPx;
		invalidate();
	}

	public int getIndicatorHeight() {
		return indicatorHeight;
	}

	public void setUnderlineColor(int underlineColor) {
		this.underlineColor = underlineColor;
		invalidate();
	}

	public void setUnderlineColorResource(int resId) {
		this.underlineColor = getResources().getColor(resId);
		invalidate();
	}

	public int getUnderlineColor() {
		return underlineColor;
	}

	public void setDividerColor(int dividerColor) {
		this.dividerColor = dividerColor;
		invalidate();
	}

	public void setDividerColorResource(int resId) {
		this.dividerColor = getResources().getColor(resId);
		invalidate();
	}

	public int getDividerColor() {
		return dividerColor;
	}

	public void setUnderlineHeight(int underlineHeightPx) {
		this.underlineHeight = underlineHeightPx;
		invalidate();
	}

	public int getUnderlineHeight() {
		return underlineHeight;
	}

	public void setDividerPadding(int dividerPaddingPx) {
		this.dividerPadding = dividerPaddingPx;
		invalidate();
	}

	public int getDividerPadding() {
		return dividerPadding;
	}

	public void setScrollOffset(int scrollOffsetPx) {
		this.scrollOffset = scrollOffsetPx;
		invalidate();
	}

	public int getScrollOffset() {
		return scrollOffset;
	}

	

	public boolean isTextAllCaps() {
		return textAllCaps;
	}

	public void setAllCaps(boolean textAllCaps) {
		this.textAllCaps = textAllCaps;
	}

	public void setTextSize(int textSizePx) {
		this.tabTextSize = textSizePx;
		updateTabStyles();
	}

	public int getTextSize() {
		return tabTextSize;
	}
	public void setTabBackground(int resId) {
		this.tabBackgroundResId = resId;
	}

	public int getTabBackground() {
		return tabBackgroundResId;
	}

	@Override
	public void onRestoreInstanceState(Parcelable state) {
		SavedState savedState = (SavedState) state;
		super.onRestoreInstanceState(savedState.getSuperState());
		currentPosition = savedState.currentPosition;
		requestLayout();
	}

	@Override
	public Parcelable onSaveInstanceState() {
		Parcelable superState = super.onSaveInstanceState();
		SavedState savedState = new SavedState(superState);
		savedState.currentPosition = currentPosition;
		return savedState;
	}

	static class SavedState extends BaseSavedState {
		int currentPosition;

		public SavedState(Parcelable superState) {
			super(superState);
		}

		private SavedState(Parcel in) {
			super(in);
			currentPosition = in.readInt();
		}

		@Override
		public void writeToParcel(Parcel dest, int flags) {
			super.writeToParcel(dest, flags);
			dest.writeInt(currentPosition);
		}

		public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
			@Override
			public SavedState createFromParcel(Parcel in) {
				return new SavedState(in);
			}

			@Override
			public SavedState[] newArray(int size) {
				return new SavedState[size];
			}
		};
	}
}
